package com.itheima.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.EmployeeHolder;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// 权限拦截器
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {


    // 访问拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取session中员工信息
        HttpSession session = request.getSession();
        Employee employee = (Employee) session.getAttribute(Constant.SESSION_EMPLOYEE);
        // 2.判断未登录
        if (employee==null) {
            // 拦截，返回错误信息
            ResultInfo resultInfo = ResultInfo.error("NOTLOGIN");
            // 将结果转换json
            ObjectMapper objectMapper = new ObjectMapper();
            String json = objectMapper.writeValueAsString(resultInfo);
            // 通过response响应
            response.setContentType("application/json;charset=utf-8"); // 告诉前端MIME类型和字符集编码
            response.getWriter().write(json);
            return false;
        }
        // 3. 登录成功，放行
        EmployeeHolder.set(employee);  //存储到当前对象
        return true;
    }

    //响应之前 删除线程内得员工对象

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        EmployeeHolder.remove();
    }
}